package com.maltys.tree;

import com.maltys.tree.base.TreeNode;

/**
 * @author Maltyts
 * @link <a href="https://leetcode.cn/problems/maximum-binary-tree/">...</a>
 */
public class ConstructMaxTree {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return build(nums, 0, nums.length - 1);
    }

    private TreeNode build(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        if (left == right) {
            return new TreeNode(nums[left]);
        }
        int max = Integer.MIN_VALUE;
        int maxIdx = Integer.MIN_VALUE;
        for (int i = left; i <= right; i++) {
            if (nums[i] > max) {
                max = nums[i];
                maxIdx = i;
            }
        }
        TreeNode root = new TreeNode(max);
        root.left = build(nums, left, maxIdx - 1);
        root.right = build(nums, maxIdx + 1, right);
        return root;
    }
}
